/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.wiki;

import fitnesse.wikitext.WikiWidget;
import fitnesse.wikitext.widgets.ParentWidget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;

import java.util.regex.Pattern;

import org.xptracker.domain.Domain;
import org.apache.commons.lang.StringUtils;

public class WikiWordWidget extends WikiWidget {
  public static final String REGEXP = "[A-Z][A-Za-z0-9]+[A-Z][A-Za-z0-9]+";
  public static final Pattern WIKI_WORD_PATTERN = Pattern.compile(REGEXP);

  @Inject
  @Named("history-depth")
  private Provider<String> depth;

  @Inject
  private Domain domain;

  @Inject
  @Named("context-path")
  private String base;

  private String content;

  public WikiWordWidget(ParentWidget parentWidget, String content) {
    super(parentWidget);
    this.content = content;
  }

  public String render() throws Exception {
    String url = base + "/Wiki.action?name=" + content;
    if (StringUtils.isNotBlank(depth.get())) {
      url += "&depth=" + depth.get();
    }
    if (domain.wikiPageExists(content)) {
      return "<a class=\"print\" href=\"" + url + "\">" + content + "</a>";
    } else {
      return content + "<a class=\"print\" href=\"" + url + "&edit=\">?</a>";
    }
  }
}
